<template>
  <div class="role-management">
    <div class="page-header">
      <h1 class="page-title">角色管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
      </div>
    </div>

    <!-- 角色列表 -->
    <el-card>
      <el-table :data="roleList" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="权限" min-width="300">
          <template #default="scope">
            <div class="permissions-tags">
              <el-tag
                v-for="permission in scope.row.permissions.slice(0, 3)"
                :key="permission"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px"
              >
                {{ permission }}
              </el-tag>
              <el-tag
                v-if="scope.row.permissions.length > 3"
                size="small"
                type="info"
              >
                +{{ scope.row.permissions.length - 3 }}个权限
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="warning"
              @click="managePermissions(scope.row)"
            >
              权限设置
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteRole(scope.row)"
              :disabled="scope.row.isSystem"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitRoleForm"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="showPermissionDialog"
      title="权限设置"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="permission-dialog">
        <div class="current-role">
          <strong>当前角色:</strong> {{ currentRole?.name }}
        </div>

        <el-divider />

        <div class="permission-tree">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :props="treeProps"
            :default-checked-keys="checkedPermissions"
            @check="handlePermissionCheck"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermissionDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="savePermissions"
            :loading="permissionLoading"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";

const roleList = ref([]);
const loading = ref(false);
const showCreateDialog = ref(false);
const showPermissionDialog = ref(false);
const editingRole = ref(null);
const currentRole = ref(null);
const submitLoading = ref(false);
const permissionLoading = ref(false);
const roleFormRef = ref();
const permissionTreeRef = ref();

const roleForm = reactive({
  name: "",
  description: "",
});

const roleRules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 50, message: "角色名称长度在2到50个字符", trigger: "blur" },
  ],
};

// 权限树数据
const permissionTree = ref([
  {
    id: "user",
    label: "用户管理",
    children: [
      { id: "user:view", label: "查看用户" },
      { id: "user:create", label: "创建用户" },
      { id: "user:edit", label: "编辑用户" },
      { id: "user:delete", label: "删除用户" },
    ],
  },
  {
    id: "role",
    label: "角色管理",
    children: [
      { id: "role:view", label: "查看角色" },
      { id: "role:create", label: "创建角色" },
      { id: "role:edit", label: "编辑角色" },
      { id: "role:delete", label: "删除角色" },
      { id: "role:permission", label: "权限管理" },
    ],
  },
  {
    id: "knowledge",
    label: "知识管理",
    children: [
      { id: "knowledge:category:view", label: "查看分类" },
      { id: "knowledge:category:manage", label: "管理分类" },
      { id: "knowledge:article:view", label: "查看文章" },
      { id: "knowledge:article:manage", label: "管理文章" },
      { id: "knowledge:video:view", label: "查看视频" },
      { id: "knowledge:video:manage", label: "管理视频" },
      { id: "knowledge:question:view", label: "查看题库" },
      { id: "knowledge:question:manage", label: "管理题库" },
    ],
  },
  {
    id: "event",
    label: "事件管理",
    children: [
      { id: "event:type:view", label: "查看事件类型" },
      { id: "event:type:manage", label: "管理事件类型" },
      { id: "event:record:view", label: "查看事件记录" },
      { id: "event:record:manage", label: "管理事件记录" },
    ],
  },
  {
    id: "volunteer",
    label: "志愿者管理",
    children: [
      { id: "volunteer:application:view", label: "查看申请" },
      { id: "volunteer:application:review", label: "审核申请" },
      { id: "volunteer:info:view", label: "查看信息" },
      { id: "volunteer:info:manage", label: "管理信息" },
      { id: "volunteer:skill:manage", label: "技能管理" },
    ],
  },
  {
    id: "notification",
    label: "通知管理",
    children: [
      { id: "notification:send", label: "发送通知" },
      { id: "notification:history", label: "查看历史" },
    ],
  },
  {
    id: "file",
    label: "文件管理",
    children: [
      { id: "file:upload", label: "上传文件" },
      { id: "file:view", label: "查看文件" },
      { id: "file:delete", label: "删除文件" },
    ],
  },
  {
    id: "system",
    label: "系统设置",
    children: [
      { id: "system:setting", label: "系统设置" },
      { id: "system:statistics", label: "查看统计" },
    ],
  },
]);

const treeProps = {
  children: "children",
  label: "label",
};

const checkedPermissions = ref([]);

const dialogTitle = computed(() => {
  return editingRole.value ? "编辑角色" : "新增角色";
});

// 模拟数据
const mockRoles = [
  {
    id: 1,
    name: "超级管理员",
    description: "拥有系统所有权限",
    permissions: [
      "user:view",
      "user:create",
      "user:edit",
      "user:delete",
      "role:view",
      "role:create",
      "role:edit",
      "role:delete",
      "role:permission",
      "knowledge:category:view",
      "knowledge:category:manage",
      "knowledge:article:view",
      "knowledge:article:manage",
      "knowledge:video:view",
      "knowledge:video:manage",
      "knowledge:question:view",
      "knowledge:question:manage",
      "event:type:view",
      "event:type:manage",
      "event:record:view",
      "event:record:manage",
      "volunteer:application:view",
      "volunteer:application:review",
      "volunteer:info:view",
      "volunteer:info:manage",
      "volunteer:skill:manage",
      "notification:send",
      "notification:history",
      "file:upload",
      "file:view",
      "file:delete",
      "system:setting",
      "system:statistics",
    ],
    createdAt: "2025-01-01 10:00:00",
    isSystem: true,
  },
  {
    id: 2,
    name: "管理员",
    description: "拥有大部分管理权限",
    permissions: [
      "user:view",
      "user:create",
      "user:edit",
      "role:view",
      "knowledge:category:view",
      "knowledge:category:manage",
      "knowledge:article:view",
      "knowledge:article:manage",
      "knowledge:video:view",
      "knowledge:video:manage",
      "knowledge:question:view",
      "knowledge:question:manage",
      "event:type:view",
      "event:type:manage",
      "event:record:view",
      "event:record:manage",
      "volunteer:application:view",
      "volunteer:application:review",
      "volunteer:info:view",
      "volunteer:info:manage",
      "notification:send",
      "notification:history",
      "file:upload",
      "file:view",
      "file:delete",
      "system:statistics",
    ],
    createdAt: "2025-01-01 10:00:00",
    isSystem: false,
  },
  {
    id: 3,
    name: "教师",
    description: "教学相关权限",
    permissions: [
      "knowledge:article:view",
      "knowledge:article:manage",
      "knowledge:video:view",
      "knowledge:video:manage",
      "knowledge:question:view",
      "knowledge:question:manage",
      "event:record:view",
      "notification:send",
      "file:upload",
      "file:view",
    ],
    createdAt: "2025-01-01 10:00:00",
    isSystem: false,
  },
  {
    id: 4,
    name: "学生",
    description: "学习相关权限",
    permissions: [
      "knowledge:article:view",
      "knowledge:video:view",
      "knowledge:question:view",
      "file:view",
    ],
    createdAt: "2025-01-01 10:00:00",
    isSystem: false,
  },
  {
    id: 5,
    name: "志愿者",
    description: "志愿者相关权限",
    permissions: ["event:record:view", "notification:history", "file:view"],
    createdAt: "2025-01-01 10:00:00",
    isSystem: false,
  },
];

const loadRoles = async () => {
  loading.value = true;
  try {
    // TODO: 调用API获取角色列表
    await new Promise((resolve) => setTimeout(resolve, 500));
    roleList.value = mockRoles;
  } catch (error) {
    console.error("加载角色列表失败:", error);
    ElMessage.error("加载角色列表失败");
  } finally {
    loading.value = false;
  }
};

const editRole = (role: any) => {
  editingRole.value = role;
  Object.assign(roleForm, {
    name: role.name,
    description: role.description,
  });
  showCreateDialog.value = true;
};

const managePermissions = (role: any) => {
  currentRole.value = role;
  checkedPermissions.value = role.permissions || [];
  showPermissionDialog.value = true;
};

const deleteRole = async (role: any) => {
  if (role.isSystem) {
    ElMessage.warning("系统角色不能删除");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // TODO: 调用API删除角色
    console.log("删除角色:", role.id);
    const index = roleList.value.findIndex((r) => r.id === role.id);
    if (index > -1) {
      roleList.value.splice(index, 1);
    }
    ElMessage.success("删除成功");
  } catch (error) {
    console.log("取消删除");
  }
};

const submitRoleForm = async () => {
  if (!roleFormRef.value) return;

  await roleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true;
      try {
        if (editingRole.value) {
          // 编辑角色
          console.log("编辑角色:", roleForm);
          // TODO: 调用API更新角色
        } else {
          // 新增角色
          console.log("新增角色:", roleForm);
          // TODO: 调用API创建角色
        }

        showCreateDialog.value = false;
        resetRoleForm();
        loadRoles();
        ElMessage.success("操作成功");
      } catch (error) {
        console.error("提交失败:", error);
        ElMessage.error("操作失败");
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const resetRoleForm = () => {
  editingRole.value = null;
  Object.assign(roleForm, {
    name: "",
    description: "",
  });
  roleFormRef.value?.clearValidate();
};

const handlePermissionCheck = (data: any, checked: any) => {
  // 更新选中的权限
  checkedPermissions.value = permissionTreeRef.value?.getCheckedKeys() || [];
};

const savePermissions = async () => {
  if (!currentRole.value) return;

  permissionLoading.value = true;
  try {
    // TODO: 调用API保存权限设置
    console.log("保存权限:", currentRole.value.id, checkedPermissions.value);
    currentRole.value.permissions = checkedPermissions.value;
    showPermissionDialog.value = false;
    ElMessage.success("权限设置保存成功");
  } catch (error) {
    console.error("保存权限失败:", error);
    ElMessage.error("保存失败");
  } finally {
    permissionLoading.value = false;
  }
};

// 初始化加载
onMounted(() => {
  loadRoles();
});

// 监听对话框关闭重置表单
watch(showCreateDialog, (newVal) => {
  if (!newVal) {
    resetRoleForm();
  }
});
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.permissions-tags {
  display: flex;
  flex-wrap: wrap;
}

.permission-dialog {
  max-height: 400px;
  overflow-y: auto;
}

.current-role {
  font-size: 16px;
  margin-bottom: 10px;
}

.permission-tree {
  max-height: 300px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
